package com.kingyun.gpsinspection.purificationservice.services.som.innerservice.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cqhilink.api.common.utils.UniqueUtil;
import com.cqhilink.api.common.utils.date.DateStyle;
import com.cqhilink.api.common.utils.date.DateUtil;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.HomePageItemMapper;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.HomePageOrderMapper;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.ManufactureMapper;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.OpcPropertyMapper;
import com.kingyun.gpsinspection.purificationservice.facade.model.*;
import com.kingyun.gpsinspection.purificationservice.facade.service.som.ManufactureService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by yangcs on 2017/12/27.
 */
public class ManufactureServiceImpl implements ManufactureService {

    @Value("#{configProperties['open_date']}")
    private String openDate;
    @Autowired
    private ManufactureMapper manufactureMapper;
    @Autowired
    private HomePageItemMapper homePageItemMapper;
    @Autowired
    private HomePageOrderMapper homePageOrderMapper;
    @Autowired
    private OpcPropertyMapper opcPropertyMapper;

    @Override
    public JSONArray manufacture() throws Exception {
        JSONArray array = new JSONArray();
        JSONArray dataStatistics = new JSONArray();
        JSONObject obj = new JSONObject();
        Manufacture day = manufactureMapper.queryByDay(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD));
        Manufacture year = manufactureMapper.queryCount();
        //原料气年累积量
        JSONObject ylqnljl = new JSONObject();
        ylqnljl.put("name", "原料气年累积量");
        ylqnljl.put("value", year == null || year.getYlqrcl() == null ? "" : year.getYlqrcl());
        ylqnljl.put("unit", "万方");
        dataStatistics.add(ylqnljl);
        //液流年销售量
        JSONObject ylnxsl = new JSONObject();
        ylnxsl.put("name", "液流年销售量");
        ylnxsl.put("value", year == null || year.getYlrxl() == null ? "" : year.getYlrxl());
        ylnxsl.put("unit", "吨");
        dataStatistics.add(ylnxsl);
        //加工损失率
        JSONObject jgsxl = new JSONObject();
        jgsxl.put("name", "加工损失率");
        if (day == null || day.getYlqrcl() == null) {
            jgsxl.put("value", "-");
        } else {
            jgsxl.put("value", day.getYlqrcl().subtract(day.getJhqrcl() == null ? new BigDecimal(0) : day.getJhqrcl()).divide(day.getYlqrcl(), 4, BigDecimal.ROUND_HALF_UP).doubleValue() * 100);
        }
        jgsxl.put("unit", "%");
        dataStatistics.add(jgsxl);
        obj.put("dataStatistics", dataStatistics);
        //安全生产天数
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date d1 = df.parse(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD));
        Date d2 = df.parse(openDate);
        long diff = d1.getTime() - d2.getTime();//这样得到的差值是微秒级别
        long days = diff / (1000 * 60 * 60 * 24);
        obj.put("days", days);
        array.add(obj);
        return array;
    }

    @Override
    public JSONArray manufactureEdit() throws Exception {
        JSONArray array = new JSONArray();
        JSONArray dataStatistics = new JSONArray();
        JSONObject obj = new JSONObject();
        Manufacture day = manufactureMapper.queryByDay(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD));
        //原料气日产量
        JSONObject ylqnljl = new JSONObject();
        ylqnljl.put("name", "原料气日产量");
        ylqnljl.put("value", day == null || day.getYlqrcl() == null ? "" : day.getYlqrcl());
        ylqnljl.put("unit", "万方");
        ylqnljl.put("dataType", "ylqrcl");
        dataStatistics.add(ylqnljl);
        //液流日销量
        JSONObject ylnxsl = new JSONObject();
        ylnxsl.put("name", "液流日销量");
        ylnxsl.put("value", day == null || day.getYlrxl() == null ? "" : day.getYlrxl());
        ylnxsl.put("unit", "吨");
        ylnxsl.put("dataType", "ylrxl");
        dataStatistics.add(ylnxsl);
        //净化气日产量
        JSONObject jgsxl = new JSONObject();
        jgsxl.put("name", "净化气日产量");
        jgsxl.put("value", day == null || day.getJhqrcl() == null ? "" : day.getJhqrcl());
        jgsxl.put("unit", "万方");
        jgsxl.put("dataType", "jhqrcl");
        dataStatistics.add(jgsxl);
        //I套原料气处理量
        JSONObject yt = new JSONObject();
        yt.put("name", "I套原料气处理量");
        yt.put("value", day == null || day.getYtylq() == null ? "" : day.getYtylq());
        yt.put("unit", "万方");
        yt.put("dataType", "ytylq");
        dataStatistics.add(yt);
        //II套原料气处理量
        JSONObject et = new JSONObject();
        et.put("name", "II套原料气处理量");
        et.put("value", day == null || day.getEtylq() == null ? "" : day.getEtylq());
        et.put("unit", "万方");
        et.put("dataType", "etylq");
        dataStatistics.add(et);
        obj.put("dataStatistics", dataStatistics);
        //安全生产天数
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date d1 = df.parse(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD));
        Date d2 = df.parse(openDate);
        long diff = d1.getTime() - d2.getTime();//这样得到的差值是微秒级别
        long days = diff / (1000 * 60 * 60 * 24);
        obj.put("days", days);
        array.add(obj);
        return array;
    }

    @Override
    public int saveManufacture(Manufacture manufacture) {
        int i;
        Manufacture day = manufactureMapper.queryByDay(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD));
        if (day == null) {
            manufacture.setManufactureId(UniqueUtil.uuid());
            manufacture.setManufactureDate(new Date());
            i = manufactureMapper.insertSelective(manufacture);
        } else {
            manufacture.setManufactureId(day.getManufactureId());
            i = manufactureMapper.updateByPrimaryKeySelective(manufacture);
        }
        return i;
    }

    @Override
    public JSONObject homepageItemData(int itemType) {
        JSONObject jsonObject = new JSONObject();
        List<HomePageItem> list = homePageItemMapper.querySelectList(itemType);
        jsonObject.put("total", list.size());
        jsonObject.put("rows", JSON.toJSON(list));
        return jsonObject;
    }

    @Override
    public JSONObject queryByOrgId() {
        JSONObject obj = new JSONObject();
        List<HomePageOrder> list;
        // 净化班组
        list = homePageOrderMapper.queryByOrgId("D3323DF8DDC8446A90AEB5392020FCF4");
        if (list == null || list.size() == 0) {
            obj.put("jhyc", 0);
            obj.put("jh", 0);
        } else {
            for (HomePageOrder h : list) {
                if (h.getIsYc() == 1) {
                    obj.put("jhyc", h.getCounts());
                } else {
                    obj.put("jh", h.getCounts());
                }
            }
            if (obj.getInteger("jhyc") == null) {
                obj.put("jhyc", 0);
            }
            if (obj.getInteger("jh") == null) {
                obj.put("jh", 0);
            }
        }

        // 电气班组
        list = homePageOrderMapper.queryByOrgId("CA652072F84A4D26942F5EC2A5356E2D");
        if (list == null || list.size() == 0) {
            obj.put("dqyc", 0);
            obj.put("dq", 0);
        } else {
            for (HomePageOrder h : list) {
                if (h.getIsYc() == 1) {
                    obj.put("dqyc", h.getCounts());
                } else {
                    obj.put("dq", h.getCounts());
                }
            }
            if (obj.getInteger("dqyc") == null) {
                obj.put("dqyc", 0);
            }
            if (obj.getInteger("dq") == null) {
                obj.put("dq", 0);
            }
        }

        // 仪表班组
        list = homePageOrderMapper.queryByOrgId("871309B9604947B9BE9F165DE47EB7C7");
        if (list == null || list.size() == 0) {
            obj.put("ybyc", 0);
            obj.put("yb", 0);
        } else {
            for (HomePageOrder h : list) {
                if (h.getIsYc() == 1) {
                    obj.put("ybyc", h.getCounts());
                } else {
                    obj.put("yb", h.getCounts());
                }
            }
            if (obj.getInteger("ybyc") == null) {
                obj.put("ybyc", 0);
            }
            if (obj.getInteger("yb") == null) {
                obj.put("yb", 0);
            }
        }

        // 机修班组
        list = homePageOrderMapper.queryByOrgId("DA1D2710D2744A79BAC25DE8063BA8C3");
        if (list == null || list.size() == 0) {
            obj.put("jxyc", 0);
            obj.put("jx", 0);
        } else {
            for (HomePageOrder h : list) {
                if (h.getIsYc() == 1) {
                    obj.put("jxyc", h.getCounts());
                } else {
                    obj.put("jx", h.getCounts());
                }
            }
            if (obj.getInteger("jxyc") == null) {
                obj.put("jxyc", 0);
            }
            if (obj.getInteger("jx") == null) {
                obj.put("jx", 0);
            }
        }
        return obj;
    }

    @Override
    public JSONObject list(String name, Integer limit, Integer offset, String search) {
        JSONObject jsonObject = new JSONObject();
        Map map = new HashMap<>();
        map.put("limit", limit == null ? 10 : limit);
        map.put("offset", offset == null ? 0 : offset);
        map.put("search", search);
        if (name.equals("净化班组")) {
            map.put("orgId", "D3323DF8DDC8446A90AEB5392020FCF4");
        } else if (name.equals("机修班组")) {
            map.put("orgId", "DA1D2710D2744A79BAC25DE8063BA8C3");
        } else if (name.equals("电气班组")) {
            map.put("orgId", "CA652072F84A4D26942F5EC2A5356E2D");
        } else if (name.equals("仪表班组")) {
            map.put("orgId", "871309B9604947B9BE9F165DE47EB7C7");
        }
        jsonObject.put("total", homePageOrderMapper.queryCount(map));
        jsonObject.put("rows", JSON.toJSON(homePageOrderMapper.queryList(map)));
        return jsonObject;
    }

    /**
     * 查询所有的OPC点
     *
     * @throws Exception
     */
    @Override
    public List<OpcPropertyVo> queryOpcConfiguration() throws Exception {
        List<OpcPropertyVo> list = new ArrayList<>();
        List<OpcProperty> returnList1 = opcPropertyMapper.queryOpcConfiguration();
        List<HomePageItem> returnList2 = homePageItemMapper.queryHomePageItem();
        formatReturnData(list, returnList1, returnList2);
        return list;
    }

    /**
     * 格式化数据
     *
     * @param list
     * @param returnList1
     * @param returnList2
     */
    private void formatReturnData(List<OpcPropertyVo> list, List<OpcProperty> returnList1, List<HomePageItem> returnList2) {
        for (OpcProperty opcProperty : returnList1) {
            OpcPropertyVo opcPropertyVo = new OpcPropertyVo();
            opcPropertyVo.setOpcPropertyId(opcProperty.getOpcPropertyId());
            opcPropertyVo.setOpcPropertyItem(opcProperty.getOpcPropertyItem());
            for (HomePageItem homePageItem : returnList2) {
                if (homePageItem.getOpcPropertyId().equals(opcProperty.getOpcPropertyId()) && homePageItem.getItemType() == 1) {
                    opcPropertyVo.setType1(true);
                }
                if (homePageItem.getOpcPropertyId().equals(opcProperty.getOpcPropertyId()) && homePageItem.getItemType() == 2) {
                    opcPropertyVo.setType2(true);
                }
            }
            list.add(opcPropertyVo);
        }
    }

    /**
     * 保存OPC首页配置
     *
     * @param items1
     * @param items2
     */
    @Override
    public Integer saveItems(String items1, String items2) throws Exception {
        List<HomePageItem> list = new ArrayList<>();
        //格式化数据
        formatData(list, items1, items2);
        //先批量删除
        homePageItemMapper.deleteList();
        //在批量插入
        if (list.size() > 0) {
            return homePageItemMapper.insertList(list);
        }
        return 0;
    }

    /**
     * 格式化数据
     *
     * @param list
     * @param items1
     * @param items2
     */
    private void formatData(List<HomePageItem> list, String items1, String items2) {
        JSONArray array1 = StringUtils.isEmpty(items1) ? new JSONArray() : JSON.parseArray(items1);
        JSONArray array2 = StringUtils.isEmpty(items2) ? new JSONArray() : JSON.parseArray(items2);
        //质量数据
        for (Object o : array1) {
            HomePageItem homePageItem = new HomePageItem();
            JSONObject obj = (JSONObject) o;
            homePageItem.setHomepageItemId(UniqueUtil.uuid());
            homePageItem.setItemType(1);
            homePageItem.setOpcPropertyId(obj.get("id").toString());
            list.add(homePageItem);
        }
        //环保数据
        for (Object o : array2) {
            HomePageItem homePageItem = new HomePageItem();
            JSONObject obj = (JSONObject) o;
            homePageItem.setHomepageItemId(UniqueUtil.uuid());
            homePageItem.setItemType(2);
            homePageItem.setOpcPropertyId(obj.get("id").toString());
            list.add(homePageItem);
        }
    }
}
